import Editor from '@/components/Editor';
import { Badge, Button, Space, Typography } from 'antd';
import cls from 'classnames';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import styles from './index.less';

const Executions = ({ data }) => {
  const [active, setActive] = useState(() => {
    return data?.[0]?.id;
  });
  const result = useMemo(() => {
    return data?.find((item) => item.id === active);
  }, [active]);

  return (
    <div className={styles.executions}>
      <div className="list-zone">
        {data?.map?.((item) => {
          return (
            <div
              key={item.id}
              className={cls('list-item', { active: item.id === active })}
            >
              <Button
                size="large"
                type={item.id === active ? 'link' : 'text'}
                block
                onClick={() => setActive(item.id)}
              >
                <div className="li-wrapper">
                  <Space>
                    <span>
                      {item.error ? (
                        <Badge color="red" />
                      ) : (
                        <Badge color="green" />
                      )}
                    </span>
                    <span>{item.id}</span>
                  </Space>
                  <span className="li-time">
                    {dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')}
                  </span>
                </div>
              </Button>
            </div>
          );
        })}
      </div>
      <div className="execution-zone">
        {result && (
          <>
            <div className="ez-card code-card">
              <Editor value={result.code} readOnly />
            </div>
            <div className="ez-card result-card">
              <Space direction="vertical" style={{ width: '100%' }}>
                {result.error ? (
                  <>
                    <Typography.Title level={3} type="danger">
                      Error
                    </Typography.Title>
                    <pre>{result.error}</pre>
                  </>
                ) : (
                  <>
                    <Typography.Title level={3} type="success">
                      Success
                    </Typography.Title>
                    <pre>{result.output}</pre>
                  </>
                )}
              </Space>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default Executions;
